<?php

class Products_IndexController extends App_Controller_Action { 
/**
     * Отображает главную страницу
     */
    public function indexAction() 
    {
    	global $prodCategories;
        $catId = $this->_getParam('catId');
        if ($catId!=1&&$catId!=2&&$catId!=3) $catId = 1;
    	$modelProducts = new Products();
    	$products = $modelProducts->getProductsByCatId($catId);
    	$this->view->catname = $prodCategories[$catId];
        $this->view->products = $products;
    }

    /**
     * Страница из меню
     */    
    public function viewAction() 
    {
        $productId = $this->_getParam('productId');
        $modelProducts = new Products();
        $product = $modelProducts->getProduct($productId);
        $this->view->product = $product;
    }

    public function adminlistAction() {
    	if (!$this->isAuth()) {	$this->_helper->redirector->gotoRoute(array(), 'adminLogin'); }
    	$modelProducts = new Products();
    	$products = $modelProducts->getProducts();
        $this->view->products = $products;
    }
    
    public function adminformAction() {
    	if (!$this->isAuth()) {	$this->_helper->redirector->gotoRoute(array(), 'adminLogin'); }
    	if ($this->_request->isPost()) {
    		$formProduct = new FormProducts('');
    		if ($formProduct->isValid($this->_getAllParams())) {
    			$post = $this->_request->getPost();
    			$product = new Products();
    			$product->setDataFromArray($post);
    			if ($product->id) {
	    			$product->update();
	    		} else {
    				$product->insert();
	    		}
	    		$uploadedData = $formProduct->getValues();
	    		if ($formProduct->fname->getFileName()) {
	    			$product->photo->delPhotoesByRefid();
    				$product->photo->addFile($formProduct->fname);
	    		}
	    		$this->_helper->redirector->gotoRoute(array(), 'adminProducts');
    		}
			$this->view->formProducts = $formProduct;
    	} else {
	    	$id = $this->_getParam('productId');
	        $modelProducts = new Products();
	        $product = $modelProducts->getProduct($id);
	        $this->view->product = $product;
			$formProducts = new FormProducts($product);
			$this->view->formProducts = $formProducts;
    	}
    }

    public function admindeleteAction() {
    	if (!$this->isAuth()) {	$this->_helper->redirector->gotoRoute(array(), 'adminLogin'); }
    	$id = $this->_getParam('productId');
        $modelProducts = new Products();
        $res = $modelProducts->delete('id='.$id);
		$this->_helper->redirector->gotoRoute(array(), 'adminProducts');
    }
}
